﻿using System.ServiceModel;

namespace CredentialsManager
{
    /// <summary>
    /// Helper class for creating and cleaning up proxies
    /// </summary>
    public static class ProxyFactory
    {
        #region Public methods

        /// <summary>
        /// Returns a proxy of type P with the required settings for this application
        /// </summary>
        /// <typeparam name="P">The required proxy class</typeparam>
        /// <typeparam name="TChannel">The interface that the proxy supports (i.e. the TChannel in ClientBase&lt;TChannel&gt;)</typeparam>
        /// <returns>A ready-to-use proxy</returns>
        public static P Create<P, TChannel>()
            where P : ClientBase<TChannel>, new()
            where TChannel : class
        {
            var proxy = new P();            

            return proxy;
        }

        /// <summary>
        /// Returns a proxy of type P with the required settings for this application
        /// </summary>
        /// <typeparam name="P">The required proxy class</typeparam>
        /// <typeparam name="TChannel">The interface that the proxy supports (i.e. the TChannel in ClientBase&lt;TChannel&gt;)</typeparam>
        /// <param name="remoteAddress">The address of the distant service</param>
        /// <returns>A ready-to-use proxy</returns>
        public static P Create<P, TChannel>(string remoteAddress)
            where P : ClientBase<TChannel>, new()
            where TChannel : class
        {
            var proxy = Create<P, TChannel>();
            proxy.Endpoint.Address = new EndpointAddress(remoteAddress);
            return proxy;
        }

        /// <summary>
        /// Cleans up the proxies
        /// </summary>
        /// <typeparam name="P">The required proxy class</typeparam>
        /// <typeparam name="TChannel">The interface that the proxy supports (i.e. the TChannel in ClientBase&lt;TChannel&gt;)</typeparam>
        /// <param name="proxy">The proxy to clean up</param>
        public static void Cleanup<P, TChannel>(P proxy)
            where P : ClientBase<TChannel>, new()
            where TChannel : class
        {
            if (proxy != null)
            {
                if (proxy.State == CommunicationState.Opened)
                {
                    try
                    {
                        proxy.Close();
                    }
                    catch
                    {
                        proxy.Abort();
                    }
                }
                else
                {
                    proxy.Abort();
                }
            }
        }

        #endregion
    }
}
